package io.elegant

import android.net.Uri
import android.os.Bundle
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import io.elegant.sessions.ActivitySession


abstract class ElegantActivity: AppCompatActivity() {
    protected abstract val clientId: String
    private var session: ActivitySession? = null
    private var fileSelectorLauncher: ActivityResultLauncher<String>? = null
    private var requestPermissionsLauncher: ActivityResultLauncher<Array<String>>? = null
    private var selectFileCallback: ((Uri?) -> Unit)? = null
    private var requestPermissionsCallback: ((Map<String, Boolean>) -> Unit)? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        fileSelectorLauncher =registerForActivityResult(ActivityResultContracts.GetContent()) {
            selectFileCallback?.let { it1 ->
                it1(it)
            }
        }
        requestPermissionsLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
        }
        connect()
    }
    override fun onDestroy() {
        session?.onDestroyedListener = null
        session?.onDestroy()
        session = null
        fileSelectorLauncher?.unregister()
        fileSelectorLauncher = null
        requestPermissionsLauncher?.unregister()
        requestPermissionsLauncher = null
        super.onDestroy()
    }
    override fun onStart() {
        super.onStart()
        session?.onStart()
    }
    override fun onStop() {
        super.onStop()
        session?.onStop()
    }
    override fun onResume() {
        super.onResume()
        session?.onResume()
    }
    override fun onPause() {
        super.onPause()
        session?.onPause()
    }
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        session?.onBackPressed {
            if (it)
                onBackPressedDispatcher.onBackPressed()
        }
    }
    abstract fun getViewGroup(): ViewGroup
    fun selectFile(mimeType: String, callback: (Uri?) -> Unit) {
        selectFileCallback = callback
        fileSelectorLauncher?.launch(mimeType)
    }
    fun requestPermissions(permissions: Array<String>, callback: (Map<String, Boolean>) -> Unit) {
        requestPermissionsCallback = callback
        requestPermissionsLauncher?.launch(permissions)
    }
    private fun connect() {
        session?.onDestroy()
        session = entry.getActivitySession(this, clientId)
        session?.onDestroyedListener = {
            // 如果连接中断就5秒后继续连接。
            getString(R.string.toast_reconnecting).let (this::toast)
            window.decorView.postDelayed(this::connect, 5000L)
        }
        session?.onCreate()
    }
}